// "配电终端"导航列表
import React, { Component } from 'react';
import { Menu, Icon, Spin, Dropdown } from 'antd';
import { connect } from 'dva';
import Media from 'react-media';
import tools from './';

let reqApi = '';

class page extends Component {
  state = {
    loading: true,
    subMenus: [],
    openKeys: [],
    menuData: {},
    firstMenuItem: '',

    // 是否已经拿到数据
    readyNav: false,
    readySensor: false,
    readyWorkshop: false,
  };

  componentWillMount() {
    reqApi = 'navList';
    const { state, props } = this;
    const payload = {
      userId: tools.funcGetUserId(),
      token: tools.funcGetToken(),
    };

    if (props[reqApi].navData.length === 0) {
      props
        .dispatch({
          type: reqApi + '/getNav',
          payload,
        })
        .then(this.funcMakeMenu);
    } else this.funcMakeMenu();

    payload.currentPage = 1;
    payload.pageSize = 1000;

    if (props[reqApi].sensorData.length === 0) {
      props
        .dispatch({
          type: reqApi + '/getSensor',
          payload,
        })
        .then(() => {
          const { state } = this;
          state.readySensor = true;
          this.funcComplete();
        });
    } else {
      state.readySensor = true;
      this.funcComplete();
    }

    if (props[reqApi].workshopData.length === 0) {
      props
        .dispatch({
          type: reqApi + '/getWorkshop',
          payload,
        })
        .then(() => {
          const { state } = this;
          state.readyWorkshop = true;
          this.funcComplete();
        });
    } else {
      state.readyWorkshop = true;
      this.funcComplete();
    }
  }

  // 生成菜单
  funcMakeMenu = () => {
    const { state, props } = this;
    const nav = props[reqApi].navData;
    if (nav.length === 0) return;

    const subMenus = [];
    const openKeys = [];
    const menuData = {};
    let firstMenuItem = '';

    for (let i = 0; i < nav.length; i += 1) {
      if (openKeys.length === 0) openKeys.push(nav[i].id);

      const items = [];

      for (let j = 0; j < nav[i].children.length; j += 1) {
        const item = nav[i].children[j];
        let { id } = item;
        id = id.substr(id.length - 4);
        menuData[id] = item.name;
        if (firstMenuItem === '') firstMenuItem = id;

        items.push(
          <Menu.Item key={id}>
            <span>
              <Icon type={item.icon} />
              <span title={id}>{item.name}</span>
            </span>
          </Menu.Item>
        );
      }

      subMenus.push(
        <Menu.SubMenu
          key={nav[i].id}
          title={
            <span>
              <Icon type={nav[i].icon} />
              <span>{nav[i].name}</span>
            </span>
          }
        >
          {items}
        </Menu.SubMenu>
      );
    }

    if (props[reqApi].navSelectedKey === '') {
      props.dispatch({
        type: reqApi + '/updateSingle',
        stateName: 'navSelectedKey',
        value: firstMenuItem,
      });
      state.firstMenuItem = firstMenuItem;
    } else {
      state.firstMenuItem = props[reqApi].navSelectedKey;
    }

    this.setState(
      {
        loading: false,
        subMenus,
        openKeys,
        menuData,
        readyNav: true,
      },
      this.funcComplete
    );
  };

  funcComplete = () => {
    const { state, props } = this;
    // 3个网络请求只要有1个未就绪就不往下执行
    if (!state.readyNav || !state.readySensor || !state.readyWorkshop) return;

    const { navData, sensorData } = props[reqApi];
    if (!props.onLoad || navData.length === 0 || sensorData.length === 0) return;

    const { firstMenuItem, menuData } = state;
    const { nodeData, wsData } = this.funcFilter(firstMenuItem);
    if (props.onLoad) props.onLoad(firstMenuItem, menuData, nodeData, wsData);
  };

  // 过滤, 只返回当前"配电终端"下的"监测节点"和"用电车间"
  funcFilter = terminalCode => {
    const { props } = this;
    const { sensorData, workshopData } = props[reqApi];
    const nodeData = [],
      wsData = [];
    for (let i = sensorData.length - 1; i >= 0; i -= 1) {
      const item = sensorData[i];
      if (item.terminalCode === terminalCode)
        nodeData.push([item.nodeCode, item.name, item.dataType]);
    }
    if (workshopData.length) {
      for (let i = workshopData.length - 1; i >= 0; i -= 1) {
        const item = workshopData[i];
        if (item.terminalCode === terminalCode) wsData.push([item.code, item.name]);
      }
    }

    return { nodeData, wsData };
  };

  // 菜单点选
  funcMenuClick = ({ key }) => {
    const { props } = this;
    props
      .dispatch({
        type: reqApi + '/updateSingle',
        stateName: 'navSelectedKey',
        value: key,
      })
      .then(() => {
        if (props.onSelect) {
          const { nodeData, wsData } = this.funcFilter(key);
          props.onSelect(key, nodeData, wsData);
        }
      });
  };

  render() {
    const { state, props } = this;
    const domMenu = (
      <Spin spinning={state.loading}>
        <Menu
          mode={props.mode || 'inline'}
          openKeys={state.openKeys}
          selectedKeys={[props[reqApi].navSelectedKey]}
          onClick={this.funcMenuClick}
          onOpenChange={openKeys => {
            this.setState({ openKeys });
          }}
        >
          {state.subMenus}
        </Menu>
      </Spin>
    );

    return (
      <Media query="(max-width: 599px)">
        {isMobile =>
          isMobile ? (
            <Dropdown overlay={domMenu} trigger={['click']}>
              <div style={{ height: 24, lineHeight: '24px' }}>
                <Icon type="database" style={{ fontSize: 16 }} />
                <span> {state.menuData[props[reqApi].navSelectedKey]}</span>
                <Icon type="down" />
              </div>
            </Dropdown>
          ) : (
            domMenu
          )
        }
      </Media>
    );
  }
}

export default connect(({ navList }) => ({ navList }))(page);
